package com.test.prolenders.fragment_prolenders.ln_state_prolenders;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.prolenders.R;
import com.test.prolenders.activity_prolenders.ln_prolenders.MainActivity_prolenders;
import com.test.prolenders.base_prolenders.BaseLnFragment_prolenders;
import com.test.prolenders.bean_prolenders.config_prolenders.AppShowCustomize_prolenders;
import com.test.prolenders.bean_prolenders.config_prolenders.RecommendAppInfo_prolenders;
import com.test.prolenders.bean_prolenders.process_prolenders.ProcessInfo_prolenders;
import com.test.prolenders.bean_prolenders.star_dialog_prolenders.ActiveWindowConfig_prolenders;
import com.test.prolenders.bean_prolenders.star_dialog_prolenders.NormalWindowConfig_prolenders;
import com.test.prolenders.bean_prolenders.userinfo_prolenders.AccountList_Fr_prolenders;
import com.test.prolenders.bean_prolenders.userinfo_prolenders.BankAccount_Fr_prolenders;
import com.test.prolenders.bean_prolenders.userinfo_prolenders.LnAplyDetailInfo_prolenders;
import com.test.prolenders.bean_prolenders.userinfo_prolenders.OthersInfo_prolenders;
import com.test.prolenders.config_prolenders.CountryConfig_prolenders;
import com.test.prolenders.config_prolenders.UserState_prolenders;
import com.test.prolenders.dialog_prolenders.BindAccountChannelDialog_Fr_prolenders;
import com.test.prolenders.dialog_prolenders.BindAccountDialog_Fr_prolenders;
import com.test.prolenders.dialog_prolenders.CustomerServiceDialog_prolenders;
import com.test.prolenders.dialog_prolenders.DeleteAccountDialog_Fr_prolenders;
import com.test.prolenders.dialog_prolenders.RateActiveDialog_prolenders;
import com.test.prolenders.dialog_prolenders.RateNormalDialog_prolenders;
import com.test.prolenders.util_prolenders.UserInfoUtil_prolenders;
import com.test.prolenders.util_prolenders.http_prolenders.HttpUtil_prolenders;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LnStateWaitFragment_prolenders extends BaseLnFragment_prolenders {

    private ImageView stateImageIv;
    private TextView stateTitleTv,stateTextTv;
    private TextView lnAmountTv,lnTermTv;
    private View tipsView;
    private TextView tipsTitleTv,tipsTextTv;
    private LinearLayout accountGroupLayout;
    private View addAccountBtn;
    private LinearLayout recommendAppGroupLayout;

    private String bindChannelMobile = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = "REVIEW";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ln_state_wait_prolenders, container, false);

        view.findViewById(R.id.flsw_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog_prolenders(requireContext()).show());

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.flsw_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            refreshLayout.setRefreshing(false);
            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"REFRESH_CLICK","");
            HttpUtil_prolenders.getInstance().userProcess(requireActivity(),() -> {
                String state = ProcessInfo_prolenders.getInstance().getUserState();
                if (UserState_prolenders.isStateChange(state)) {//刷新用户状态
                    FragmentActivity activity = requireActivity();
                    UserState_prolenders.clearState();
                    activity.startActivity(new Intent(activity, MainActivity_prolenders.class));
                    activity.finish();
                }else HttpUtil_prolenders.getInstance().requestLnAplyDetail(requireActivity(),() -> HttpUtil_prolenders.getInstance().requestAppSInfo(requireActivity(),this::refresh));
            });
        });

        view.findViewById(R.id.flsw_btn_refresh).setOnClickListener(v -> {
            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"REFRESH_CLICK","");
            HttpUtil_prolenders.getInstance().userProcess(requireActivity(),() ->{
                String state = ProcessInfo_prolenders.getInstance().getUserState();
                if (UserState_prolenders.isStateChange(state)) {//刷新用户状态
                    FragmentActivity activity = requireActivity();
                    UserState_prolenders.clearState();
                    activity.startActivity(new Intent(activity, MainActivity_prolenders.class));
                    activity.finish();
                }else HttpUtil_prolenders.getInstance().requestLnAplyDetail(requireActivity(),() -> HttpUtil_prolenders.getInstance().requestAppSInfo(requireActivity(),this::refresh));
            });
        });

        stateImageIv = view.findViewById(R.id.flsw_iv_stateimg);
        stateTitleTv = view.findViewById(R.id.flsw_tv_statetitle);
        stateTextTv = view.findViewById(R.id.flsw_tv_statetext);
        lnAmountTv = view.findViewById(R.id.flsw_tv_lnamount);
        lnTermTv = view.findViewById(R.id.flsw_tv_lnterm);
        tipsView = view.findViewById(R.id.flsw_view_tips);
        tipsTitleTv = view.findViewById(R.id.flsw_tv_tipstitle);
        tipsTextTv = view.findViewById(R.id.flsw_tv_tipstext);
        accountGroupLayout = view.findViewById(R.id.flsw_layout_accountgroup);
        addAccountBtn = view.findViewById(R.id.flsw_btn_addaccount);
        recommendAppGroupLayout = view.findViewById(R.id.flsw_layout_recommendappgroup);

        init();

        return view;
    }

    private void init(){
        //初始化审核状态
        if (ProcessInfo_prolenders.getInstance().isOrderLoaning()){//状态：审核通过放款中
            page = "LOANING";
            stateImageIv.setBackgroundResource(R.drawable.img_ln_lning_prolenders);
            stateTitleTv.setText(getString(R.string.ln_wait_lning_title_prolenders));
            stateTextTv.setText(getString(R.string.ln_wait_lning_text_prolenders));
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        HttpUtil_prolenders.getInstance().requestLnAplyDetail(requireActivity(),() ->
                HttpUtil_prolenders.getInstance().requestAppSInfo(requireActivity(),this::refresh)
        );
    }

    //更新额度、日期、推荐app显示
    @SuppressLint("SetTextI18n")
    public void refresh(){
        String currency = LnAplyDetailInfo_prolenders.getInstance().getCurrency();

        lnAmountTv.setText(LnAplyDetailInfo_prolenders.getInstance().getAmount()+" "+currency);
        lnTermTv.setText(LnAplyDetailInfo_prolenders.getInstance().getTermStr(requireContext()));

        //提示文案显示
        if (LnAplyDetailInfo_prolenders.getInstance().isShowWaitTips()){
            tipsTitleTv.setText(LnAplyDetailInfo_prolenders.getInstance().getWaitTipsTitle());
            tipsTextTv.setText(LnAplyDetailInfo_prolenders.getInstance().getWaitTipsText());
            tipsView.setVisibility(View.VISIBLE);
        }

        //app推荐显示
        refreshRecommendAppList();

        //放款账户显示
        refreshAccounts();

    }

    //放款账户显示
    private void refreshAccounts(){

        accountGroupLayout.removeAllViews();

        if (CountryConfig_prolenders.getInstance().isGhana()){//加纳

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_account_show_prolenders,null);
            TextView accountTv = accountView.findViewById(R.id.ias_tv_account);
            accountTv.setText(LnAplyDetailInfo_prolenders.getInstance().getWltMobile_Gh());
            accountGroupLayout.addView(accountView);
            afterFinishInit();

        }else if (CountryConfig_prolenders.getInstance().isFrench()){//法语区

            addAccountBtn.setVisibility(View.VISIBLE);
            addAccountBtn.setOnClickListener(v -> {
                HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"ADD_CLICK","");
                new BindAccountDialog_Fr_prolenders(requireActivity(), page,
                        mobile -> {
                            bindChannelMobile = mobile;
                            HttpUtil_prolenders.getInstance().requestAccountList_Fr(requireActivity(),this::refreshAccountList_Fr);
                        }
                ).show();
            });

            HttpUtil_prolenders.getInstance().requestAccountList_Fr(requireActivity(),this::refreshAccountList_Fr);

        }else {//其他国家

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_account_show_prolenders,null);
            TextView accountTv = accountView.findViewById(R.id.ias_tv_account);
            accountTv.setText(LnAplyDetailInfo_prolenders.getInstance().getBkAccount_NiUgKe());
            accountGroupLayout.addView(accountView);
            afterFinishInit();

        }
    }

    //更新法语区绑卡列表
    public void refreshAccountList_Fr(){
        accountGroupLayout.removeAllViews();

        ArrayList<BankAccount_Fr_prolenders> accounts = AccountList_Fr_prolenders.getInstance().getBankAccountList();

        int i=0;
        while (i<2 || i<accounts.size()){

            if (i<accounts.size()) addAccount_Fr(accounts.get(i),i+1);
            else {
                View view = View.inflate(requireContext(), R.layout.item_add_account_fr_prolenders, null);
                TextView titleView = view.findViewById(R.id.iaaf_tv_title);
                titleView.append(" "+i);
                view.findViewById(R.id.iaaf_view_click).setOnClickListener(
                        v -> {
                            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"ADD_CLICK","");
                            new BindAccountDialog_Fr_prolenders(requireActivity(), page,
                                    mobile -> {
                                        bindChannelMobile = mobile;
                                        HttpUtil_prolenders.getInstance().requestAccountList_Fr(requireActivity(),this::refreshAccountList_Fr);
                                    }
                            ).show();
                        }
                );
                accountGroupLayout.addView(view);
            }

            i++;
        }

        //更新列表后，判断是否需要绑定运营商
        if (!TextUtils.isEmpty(bindChannelMobile) ){
            if (OthersInfo_prolenders.getInstance().getAddBindFlag()){
                new BindAccountChannelDialog_Fr_prolenders(requireContext(), bindChannelMobile,
                        null,
                        () -> HttpUtil_prolenders.getInstance().addAccount_Fr(
                                    requireActivity(),
                                    bindChannelMobile,
                                    bindChannelMobile,
                                    OthersInfo_prolenders.getInstance().getChannel(),
                                    () -> HttpUtil_prolenders.getInstance().requestAccountList_Fr(requireActivity(),this::refreshAccountList_Fr),
                                    false
                        )

                ).show();
                bindChannelMobile = "";
            }
        }else afterFinishInit();
    }

    //法语区添加放款卡
    private void addAccount_Fr(BankAccount_Fr_prolenders account, int num){
        if (account == null) return;

        String desc = account.getWalletDesc();

        View accountView = View.inflate(requireContext(), R.layout.item_account_fr_prolenders, null);
        TextView titleTv = accountView.findViewById(R.id.iaf_tv_title);
        ImageView logoIv = accountView.findViewById(R.id.iaf_iv_logo);
        TextView channelTv = accountView.findViewById(R.id.iaf_tv_channel);
        TextView mobileTv = accountView.findViewById(R.id.iaf_tv_mobile);
        ImageButton deleteIb = accountView.findViewById(R.id.iaf_ib_delete);

        titleTv.append(" "+num);
        mobileTv.setText(account.getWalletMobile());
        channelTv.setText(desc);

        //删除卡
        deleteIb.setOnClickListener(v -> {
            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"DELETE_CLICK",account.getWalletMobile());
            new DeleteAccountDialog_Fr_prolenders(requireActivity(),account, page,
                    () -> HttpUtil_prolenders.getInstance().requestAccountList_Fr(requireActivity(),this::refreshAccountList_Fr)).show();
        });

        accountGroupLayout.addView(accountView);

        //获取图标
        if (AppShowCustomize_prolenders.getInstance().getChannelLogoByDesc(desc) == null){
            new Thread(() -> {
                try {
                    if (TextUtils.isEmpty(account.getWalletLogo())) return;
                    if (!AppShowCustomize_prolenders.getInstance().hasAccountChannel()) return;
                    URL url = new URL(account.getWalletLogo());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        AppShowCustomize_prolenders.getInstance().setChannelLogoByDesc(desc,bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(AppShowCustomize_prolenders.getInstance().getChannelLogoByDesc(desc));

    }

    //页面显示初始化结束后获取评分弹窗配置
    private void afterFinishInit(){
        HttpUtil_prolenders.getInstance().requestStarWindowConfig(requireActivity(),this::onStarWindowConfigResponse);
    }

    //评分弹窗显示流程
    public void onStarWindowConfigResponse(){
        
        //1.活动弹窗
        if (ActiveWindowConfig_prolenders.getInstance().isSwitch() &&
                UserInfoUtil_prolenders.getInstance().getActivedialogCount()< ActiveWindowConfig_prolenders.getInstance().getNum()){
            new RateActiveDialog_prolenders((AppCompatActivity) requireActivity()).show();
            return;
        }

        //2.评价弹窗
        if (NormalWindowConfig_prolenders.getInstance().isSwitch() &&
                UserInfoUtil_prolenders.getInstance().getNormaldialogCount()< NormalWindowConfig_prolenders.getInstance().getNum()){
            new RateNormalDialog_prolenders((AppCompatActivity) requireActivity()).show();
        }

    }
    
    public void refreshRecommendAppList(){
        if (!AppShowCustomize_prolenders.getInstance().getRecommendFlag()) return;
        recommendAppGroupLayout.removeAllViews();
        ArrayList<RecommendAppInfo_prolenders> recommendAppInfos = AppShowCustomize_prolenders.getInstance().getRecommendAppList();
        for (RecommendAppInfo_prolenders recommendAppInfo:recommendAppInfos){
            addRecommendApp(recommendAppInfo);
        }
    }

    private void addRecommendApp(RecommendAppInfo_prolenders recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_recommend_app_prolenders,null);

        TextView titleTv = itemView.findViewById(R.id.ira_tv_title);
        TextView textTv = itemView.findViewById(R.id.ira_tv_text);
        ImageView logoIv = itemView.findViewById(R.id.ira_iv_logo);
        TextView appNameTv = itemView.findViewById(R.id.ira_tv_appname);
        TextView amountTextTv = itemView.findViewById(R.id.ira_tv_amounttext);
        TextView scoreTv = itemView.findViewById(R.id.ira_tv_score);
        TextView downloadsTv = itemView.findViewById(R.id.ira_tv_downloads);

        titleTv.setText(recommendAppInfo.getTitle(requireContext()));
        textTv.setText(recommendAppInfo.getText(requireContext()));
        appNameTv.setText(recommendAppInfo.getAppName());
        amountTextTv.setText(recommendAppInfo.getAmountText());
        scoreTv.setText(recommendAppInfo.getScore());
        downloadsTv.setText(recommendAppInfo.getDownloads());

        //Install按键
        itemView.findViewById(R.id.ira_btn_install).setOnClickListener(v -> {
            HttpUtil_prolenders.getInstance().saveBuriedPoint(page,"RECOMMEND_"+recommendAppInfo.getAppName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getPath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });

        //加载logo
        if (recommendAppInfo.getLogoBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getLogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLogoBitmap(bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(recommendAppInfo.getLogoBitmap());

        recommendAppGroupLayout.addView(itemView);
    }

}